﻿/*
    Copyright (C) 2008, wj2929, wj2929@gmail.com

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    *KEEP THIS HEADER INFORMATION*
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Text.RegularExpressions;

using System.IO;
using mjRegister.Entity;
using System.Threading;
using mjRegister.BAL;
using System.Collections;
using mjRegister.DataRandom;

namespace mjRegister
{
    public partial class Form1 : Form
    {
        CookieCollection cc = new CookieCollection();
        string rcode = string.Empty;
        string usercode = "";
        int curnum = 0;

        int start = 0;
        int end = 0;
        int length = 0;
        ArrayList alYear = new ArrayList();
        ArrayList alMonth = new ArrayList();
        ArrayList alDay = new ArrayList();
        ArrayList alBaseinfoprivacy = new ArrayList();
        ArrayList alStatus = new ArrayList();

        private AccountInfo _accountInfo;
        private Form2 _ownerForm;

        RegexOptions options =
            RegexOptions.IgnorePatternWhitespace |
            RegexOptions.ExplicitCapture |
              RegexOptions.Singleline
             | RegexOptions.IgnoreCase;

        VerifyCode verifyCode = new VerifyCode();

        IList<Thread> lstThread = new List<Thread>();

        public Form1(Form2 ownerForm,AccountInfo accountInfo)
        {
            _ownerForm = ownerForm;

            _accountInfo = accountInfo;

            InitializeComponent();

            for (int i = 1950; i < 2008; i++)
            {
                alYear.Add(i.ToString());
            }

            for (int i = 1; i <= 12; i++)
            {
                alMonth.Add(i.ToString().PadLeft(2,'0'));
            }
            for (int i = 1; i <= 31; i++)
            {
                alDay.Add(i.ToString().PadLeft(2, '0'));
            }
            alBaseinfoprivacy.Add("任何人能看见我的资料和内容");
            alBaseinfoprivacy.Add("仅好友能看见我的资料和内容");
            alBaseinfoprivacy.Add("隐藏我的资料和内容");
            for(int i=0;i<this.alBaseinfoprivacy.Count; i++)
            {
                this.ddlbaseinfoprivacy.Items.Add(alBaseinfoprivacy[i].ToString());
            }
            this.ddlbaseinfoprivacy.SelectedIndex = 2;

            alStatus.Add("其他");
            alStatus.Add("学生");
            alStatus.Add("已工作");
            for (int i = 0; i < this.alStatus.Count; i++)
            {
                this.ddlstatus.Items.Add(alStatus[i].ToString());
            }
            this.ddlstatus.SelectedIndex = 0;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                curnum = int.Parse(this.textBox1.Text.Trim());
            }
            catch (Exception ex)
            {
                MessageBox.Show("[当前计数]数据类型：数值。");
            }

            changeemail();
        }


        void LoadUserCodeList()
        {
            this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]获取邀请码：\n",
                DateTime.Now.ToString("HH:mm:ss"),
                string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

            User user = new User();

            this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]开始登录系统……",
                DateTime.Now.ToString("HH:mm:ss"),
                string.Format("{0}", _accountInfo.Email))));

            if (user.Login(_accountInfo))
            {
                this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]登录系统成功！",
                    DateTime.Now.ToString("HH:mm:ss"),
                    string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

                this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]开始获取邀请码：",
                    DateTime.Now.ToString("HH:mm:ss"),
                    string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

                this.Invoke(new DInitDDLUserCode(InitDDLUserCode),user.GetUserCodes());

                this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]获取邀请码完成！",
                    DateTime.Now.ToString("HH:mm:ss"),
                    string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

                user.Logout();

                this.Invoke(new DAppendText(_ownerForm.AppendText),
                    string.Format("[{0}]：[{1}]退出系统！\n",
                        DateTime.Now.ToString("HH:mm:ss"),
                        string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name)));
            }
        }
        delegate void DAppendText(string text);

        delegate void DInitDDLUserCode(IList<string> userCodes);
        void InitDDLUserCode(IList<string> userCodes)
        {
            this.comboBox1.Items.Clear();
            this.comboBox1.Items.AddRange(GetArray<string>.Get(userCodes));
            if (this.comboBox1.Items.Count > 0)
                this.comboBox1.SelectedIndex = 0;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(LoadUserCodeList));
            t.Start();
            lstThread.Add(t);

            GetExt();
        }

        public void Stop()
        {
            this.Invoke(new DAppendText(_ownerForm.AppendText),
                string.Format("[{0}]：正在中断当前执行线程……",
                    DateTime.Now.ToString("HH:mm:ss")));

            for (int i = 0; i < lstThread.Count; i++)
            {
                if (lstThread[i].IsAlive)
                    lstThread[i].Abort();
            }

            this.Invoke(new DAppendText(_ownerForm.AppendText),
                string.Format("[{0}]：中断当前执行线程完成！\n",
                    DateTime.Now.ToString("HH:mm:ss")));
        }


        public void GetExt()
        {
            try
            {
                if (this.checkBox1.Checked)
                    GenerationName();
                if (this.checkBox2.Checked)
                    GenerationBirthday();
                if (this.checkBox3.Checked)
                    GenerationCity();
                if (this.checkBox4.Checked)
                    GenerationBaseinfoprivacy();
                if (this.checkBox5.Checked)
                    GenerationStatus();
                if (this.checkBox6.Checked)
                    GenerationPassword();

                this.piccode.Image = verifyCode.GetVerifyCodeImage();

                //Random r = new Random();
                //rcode = r.NextDouble().ToString();
                ////string strExt = "";
                //HttpProc hp = new HttpProc();
                //Image img = null;
                //hp.strUrl = string.Format("http://www.kaixin001.com/interface/regcreatepng.php?randnum={0}",rcode);
                //HttpWebRequest 请求 = hp.CreateRequest();
                //HttpWebResponse 响应 = null;
                //try
                //{
                //    响应 = (HttpWebResponse)请求.GetResponse();
                //    img = Image.FromStream(响应.GetResponseStream());
                //    if (响应.Cookies.Count > 0)
                //    {
                //        cc = 响应.Cookies;
                //    }
                //    if (img != null)
                //    {
                //        this.piccode.Image = img;
                //    }
                //    //return strExt;
                //}
                //catch (Exception ex)
                //{
                //    Console.WriteLine(ex.Message);
                //}

                if (this.radioButton1.Checked)
                {
                    start = int.Parse(this.txtStart.Text.Trim());
                    end = int.Parse(this.txtEnd.Text.Trim());
                    length = int.Parse(this.txtLength.Text.Trim());

                    this.label1.Text = string.Format("总计：{0}", end - start + 1);

                    if (curnum == 0)
                        curnum = start;


                    this.lemail.Text = this.txtemail.Text.Replace("{*}", curnum.ToString().PadLeft(length, '0'));
                }
                else
                {
                    if (alEmail.Count == 0) return;
                    if (alEmail.Count > curnum - 1)
                        this.lemail.Text = alEmail[curnum - 1].ToString();
                }
                this.textBox1.Text = curnum.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error：" + ex.Message);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (verifyCode.CheckCode(this.txtcode.Text.Trim()))
            {
                //start = int.Parse(this.txtStart.Text.Trim());
                //end = int.Parse(this.txtEnd.Text.Trim());
                //length = int.Parse(this.txtLength.Text.Trim());

                usercode = this.comboBox1.Text;
                string PostUrl = "http://www.kaixin001.com/reg/reg_submit.php";
                string PostDate = string.Format("usercode={0}&rcode={1}&email={2}&password={3}&password2={3}&real_name={4}&gender={5}&year={6}&month={7}&day={8}&city={9}&status={10}&baseinfoprivacy={11}&code={12}&company={13}&school={13}",
                    usercode, verifyCode.rcode, Common.UrlEncode(this.lemail.Text), this.txtpwd.Text, this.txtreal_name.Text, this.txtgender.Text, this.txtyear.Text, this.txtmonth.Text, this.txtday.Text, Common.UrlEncode(this.txtcity.Text),
                    this.ddlstatus.SelectedIndex.ToString(), this.ddlbaseinfoprivacy.SelectedIndex.ToString(), this.txtcode.Text,Common.UrlEncode(RandomSchool.Generation()));

                HttpProc hp = new HttpProc(PostUrl, PostDate, cc);
                string ResStr1 = hp.Proc();

                if (ResStr1.IndexOf("感谢注册！请接收确认邮件以完成注册步骤") > 0)
                {
                    using (StreamWriter sw = new StreamWriter(Path.Combine(Application.StartupPath, "accounts.txt"), true, Encoding.Default))
                    {
                        sw.WriteLine(string.Format("{0} {1}", this.lemail.Text, this.txtpwd.Text));
                    }
                    curnum++;
                    MessageBox.Show("注册成功，请接收确认邮件以完成注册步骤。");
                    if (_ownerForm.htAccountInfo[lemail.Text] == null)
                    {
                        AccountInfo accountInfo = new AccountInfo
                        {
                            Email = lemail.Text,
                            Password = this.txtpwd.Text,
                            ActiveStatus = ActiveStatus.NoVerifyActive
                        };

                        Account.Add(accountInfo);

                        _ownerForm.htAccountInfo[lemail.Text] = accountInfo;

                        _ownerForm.AddAccountToAccountGroup(SystemGroup.全部.ToString(), accountInfo, false);
                        //_ownerForm.AddAccountToAccountGroup(SystemGroup.未激活或账户错误组.ToString(), accountInfo, false);
                        _ownerForm.AddAccountToAccountGroup(SystemGroup.未分组.ToString(), accountInfo, false);
                        _ownerForm.AddAccountToAccountGroup(SystemGroup.未验证组.ToString(), accountInfo, false);
                    }
                    this.txtcode.Focus();
                    if (curnum > end)
                    {
                        MessageBox.Show("批量注册完毕，请接收确认邮件以完成注册步骤。");
                        return;
                    }
                    GetExt();
                }
                else
                {
                    string regex = "<div\\s+id=\\\"main\\\".*?>\\s*(?<info>.*?)\\s*</div>";
                    Regex reg = new Regex(regex, options);
                    string message = reg.Match(ResStr1).Result("${info}");
                    MessageBox.Show(reg.Match(ResStr1).Result("${info}"));
                    if (message.IndexOf("验证码错误") > -1)
                        GetExt();
                    else if (message == "[0]: 邮件地址已经被注册" || message == "[0]: 邮件地址错误")
                    {
                        curnum++;
                        if (curnum > end)
                        {
                            MessageBox.Show("批量注册完毕，请接收确认邮件以完成注册步骤。");
                            return;
                        }
                        GetExt();
                    }
                }
                this.txtcode.Text = string.Empty;
            }
            else
                MessageBox.Show("验证码错误！");
        }

        private void txtStart_TextChanged(object sender, EventArgs e)
        {
            changeemail();
        }

        private void txtLength_TextChanged(object sender, EventArgs e)
        {
            changeemail();
        }

        void changeemail()
        {
            try
            {
                start = int.Parse(this.txtStart.Text.Trim());
                end = int.Parse(this.txtEnd.Text.Trim());
                length = int.Parse(this.txtLength.Text.Trim());

                if(curnum == 0)
                    curnum = start;

                this.label1.Text = string.Format("总计：{0}", end - start + 1);

                this.lemail.Text = this.txtemail.Text.Replace("{*}", curnum.ToString().PadLeft(length, '0'));
            }
            catch (Exception ex)
            {
                MessageBox.Show("[范围]、[长度]数据类型：数值。");
            }
 
        }

        private void txtemail_TextChanged(object sender, EventArgs e)
        {
            changeemail();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            GetExt();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string message = "email字典格式说明：\n";
            message += "email（换行）\n";
            message += "email（换行）\n";
            message += "......................\n";
            message += "email";

            MessageBox.Show(message);
        }

        ArrayList alEmail = new ArrayList();
        Hashtable htEmail = new Hashtable();
        private void button3_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if (File.Exists(openFileDialog1.FileName))
                {
                    alEmail.Clear();
                    htEmail.Clear();
                    string[] emails = File.ReadAllLines(openFileDialog1.FileName);

                    string re = "^(?<email>(?<username>[^@\\s!#\\$%\\^&\\(\\)]+)@(?<domain>(?:[-a-z0-9A-Z]+\\.)+[a-zA-Z]{2,}))$"; ;
                    for (int i = 0; i < emails.Length; i++)
                    {
                        string email = emails[i];
                        if (Regex.IsMatch(email, re))
                        {
                            if (htEmail[email] == null && _ownerForm.htAccountInfo[email] == null)
                            {
                                alEmail.Add(email);
                                htEmail[email] = email;
                            }
                        }
                    }
                    if (alEmail.Count > 0)
                    {
                        end = alEmail.Count;
                        this.lemail.Text = alEmail[0].ToString();
                        curnum = 1;
                        this.textBox1.Text = "1";
                        this.button2.Enabled = true;
                        this.label1.Text = string.Format("总计：{0}个", alEmail.Count.ToString());
                    }
                    this.radioButton2.Checked = true;
                    MessageBox.Show(string.Format("完成email导入，总计：{0}个；导入成功：{1}个；重复：{2}个", emails.Length.ToString(), alEmail.Count.ToString(), (emails.Length-alEmail.Count).ToString()));
                }
            }
        }

        private void radioButton_MouseClick(object sender, MouseEventArgs e)
        {
            RadioButton rb = (RadioButton)sender;
            switch (rb.Name)
            {
                case "radioButton1":
                    this.button2.Enabled = true;
                    changeemail();
                    break;
                case "radioButton2":
                    if (alEmail.Count != 0)
                    {
                        end = alEmail.Count;
                        curnum = curnum < 1 ? 1 : curnum;
                        this.lemail.Text = alEmail[curnum-1].ToString();
                        this.button2.Enabled = true;
                        this.label1.Text = string.Format("总计：{0}", alEmail.Count.ToString());
                    }
                    else
                    {
                        this.lemail.Text = "尚未导入email";
                        this.button2.Enabled = false;
                    }
                    break;
            }

        }

        void GenerationName()
        {
            NameSexInfo nameSexInfo = RandomName.Generation();
            this.txtreal_name.Text = nameSexInfo.Name;
            this.txtgender.Text = ((int)nameSexInfo.Sex).ToString();
        }

        void GenerationBirthday()
        {
            Random r = new Random();
            this.txtyear.Text = alYear[r.Next(0, alYear.Count)].ToString();
            this.txtmonth.Text = alMonth[r.Next(0, alMonth.Count)].ToString();
            this.txtday.Text = alDay[r.Next(0, alDay.Count)].ToString();
        }

        
        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            GenerationName();
        }

 
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Stop();
        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            GenerationBirthday();
        }

        void GenerationBaseinfoprivacy()
        {
            Random r = new Random();
            this.ddlbaseinfoprivacy.SelectedIndex = r.Next(0, alBaseinfoprivacy.Count);
        }

        private void linkLabel5_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            GenerationBaseinfoprivacy();
        }

        void GenerationStatus()
        {
            Random r = new Random();
            this.ddlstatus.SelectedIndex = r.Next(0, alStatus.Count);
        }

        void GenerationCity()
        {
            this.txtcity.Text = RandomCity.Generation(); 
        }

        private void linkLabel6_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            GenerationStatus();
        }

        private void linkLabel4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            GenerationCity();
        }

        void GenerationPassword()
        {
            this.txtpwd.Text = Guid.NewGuid().ToString().Substring(0, new Random().Next(6, 16)).Replace("-", "");
        }

        private void linkLabel7_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            GenerationPassword();
        }
    }
}
